package com.kwq.registered.controller;


import com.kwq.common.Common;
import com.kwq.feign.client.EmailClient;
import com.kwq.feign.client.UserClient;
import com.kwq.feign.pojo.User;
import com.kwq.feign.pojo.email;
import com.kwq.registered.dto.RegisteredDto;

import com.kwq.registered.tools.RedisTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.function.ToDoubleBiFunction;

import static com.kwq.registered.tools.RandomTool.randomCode;
@Slf4j
@RestController
@Api(tags = "注册服务接口")
@RequestMapping("/registered")
@Component
public class RegisteredController {
    private  final Logger logger = LoggerFactory.getLogger(RegisteredController.class);
    @Autowired
    EmailClient emailClient;
    @Autowired
    UserClient userClient;
    @Autowired
    private RedisTool redis;

    @ApiOperation(value = "发送验证码")
    @PostMapping("/sendCode")
    public Common registeredSend(User registeredDto){
        String userEmail = registeredDto.getEmail();
        String username = registeredDto.getUsername();
        //查询用户名是否存在
        Common usercommon = userClient.selectIfNameExit(username);
//        System.out.println(usercommon.toString());
        Boolean exit =(Boolean) usercommon.getData();
//        System.out.println(exit);

        // TODO: 2022/8/16 限制发送邮件次数
        if (!exit|exit==null){
            //生成六位验证码
            String randomCode = randomCode();
            // DONE: 2022/8/16 验证码存入redis
            // key: 邮箱 value：验证码
            try {
                redis.setEntity(userEmail,randomCode);
            } finally{

                // TODO: 2022/8/19  考虑将验证码放进mq，前端自动获取，提升效率
            
            //构造email信息
            String message=username+"你的验证码为："+(String) randomCode;

            //构造email对象
            email e =new email();
            e.setTitle("注册验证码");
            e.setAcceptor(userEmail);
            e.setContent(message);
            //发送邮件
            emailClient.sendEmail(e);

            //设置用户状态(注册未验证)
            registeredDto.setState(0);
            registeredDto.setPermission("1");

            List<User> user = new ArrayList<>();
            user.add(registeredDto);
            //注册用户
            userClient.saveAll(user);
            }
            return new Common(200,"success");
        }else{
            return new Common(409,"用户名已存在");
        }

    }


    @ApiOperation(value = "验证验证码")
    @PostMapping("/checkCode")
    public Common registeredCheck(RegisteredDto  registeredDto){
        String userEmail = registeredDto.getEmail();
        String username = registeredDto.getUsername();
        
        String usercode =registeredDto.getCode();
        
            // DONE: 2022/8/16 验证码取出
            // key: 邮箱 value：验证码
            String code = redis.getCode(username);
            

        if (usercode.equals(code)) {
            //构造email信息
            String message = username + "注册成功";

            //构造email对象
            email e = new email();
            e.setTitle("注册成功");
            e.setAcceptor(userEmail);
            e.setContent(message);
            

            //设置用户状态(注册已经验证)
            registeredDto.setState(1);
            registeredDto.setPermission("1");

            List<User> user = new ArrayList<>();
            user.add(registeredDto);
            //更新用户状态（已经验证）
            userClient.updateAll(user);

            //发送邮件
            emailClient.sendEmail(e);

            return new Common(200, "success");
        }else {
            return new Common(409, "验证码错误");
        }
        
    }
    
    
    
    
    
    
    
    
}
